# 窗口标题和图标设置
"""
1、pygame.display.set_caption()
作用：设置窗口的标题
参数：
    第一个参数title=传入一个字符串，
    第二个参数icontitle=传入一个图片路径
返回值：无
2、pygame.display.set_icon()
作用：设置窗口左上角的小图标
参数：一个icon的Surface对象
返回值：无
"""

# 导入必要的库
import os
import sys
import pygame

# 初始化pygame
pygame.init()

# 定义各项变量
size = width, height = 600, 400
WHITE = (255, 255, 255)
speed = [1, 1]
fps = 100
# 设置资源路径
BASE_DIR = os.path.realpath(os.path.dirname(sys.argv[0]))
BALL_DIR = os.path.join(BASE_DIR, 'ball.gif')
RAT_DIR = os.path.join(BASE_DIR, 'rat.png')  # 注意icon的要小于32
MUSIC_DIR = os.path.join(BASE_DIR, 'music.mp3')
SOUND_DIR = os.path.join(BASE_DIR, 'en.mp3')


# 设置窗体
screen = pygame.display.set_mode(size, flags=pygame.RESIZABLE)
pygame.display.set_caption('小仓鼠')
icon = pygame.image.load(RAT_DIR)
pygame.display.set_icon(icon)

# 加载音乐和音效
pygame.mixer.music.load(MUSIC_DIR)
pygame.mixer.music.play()
sound = pygame.mixer.Sound(SOUND_DIR)

# 实例化小球
ball = pygame.image.load(BALL_DIR)
ball_rect = ball.get_rect()

# 时间控制
clock = pygame.time.Clock()

# 游戏循环
while True:
    # 监听事件
    for event in pygame.event.get():
        # 退出
        if event.type == pygame.QUIT:
            sys.exit()
        # 窗口变化
        elif event.type == pygame.VIDEORESIZE:
            size = width, height = event.w, event.h
        # 按下按键
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                speed[1] -= 1
            elif event.key == pygame.K_DOWN:
                speed[1] += 1
            elif event.key == pygame.K_LEFT:
                speed[0] -= 1
            elif event.key == pygame.K_RIGHT:
                speed[0] += 1
            elif event.key == pygame.K_SPACE:
                speed[0] = 0
                speed[1] = 0
            if abs(speed[0]) > 6:
                speed[0] = 6 * int(speed[0] / abs(speed[0]))
            if abs(speed[1]) > 6:
                speed[1] = 6 * int(speed[1] / abs(speed[1]))
    # 设置小球移动
    ball_rect = ball_rect.move(speed[0], speed[1])
    # 碰壁反弹
    if ball_rect.top < 0 or ball_rect.bottom > height:
        speed[1] = -speed[1]  # 撞到墙壁就会调转方向
        pygame.mixer.Sound.play(sound)  # 撞到墙壁就会发出声音
    if ball_rect.left < 0 or ball_rect.right > width:
        speed[0] = -speed[0]
        pygame.mixer.Sound.play(sound)

    # 更新设置
    screen.fill(WHITE)
    screen.blit(ball, ball_rect)
    clock.tick(fps)
    pygame.display.update()
